/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unesp.demac.bcc.soo.servlet;

import br.unesp.demac.bcc.soo.bean.Pessoa;
import br.unesp.demac.bcc.soo.wsClient.AluguelRel;
import br.unesp.demac.bcc.soo.wsClient.Dvd;
import br.unesp.demac.bcc.soo.wsClient.LocadoraWS_Service;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;
import org.json.JSONObject;

/**
 *
 * @author flavioam
 */
public class relatorios extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/LocadoraWS/LocadoraWS.wsdl")
    private LocadoraWS_Service service;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String relatorio = request.getParameter("relatorio");

            HttpSession session = request.getSession();

            Pessoa p = (Pessoa) session.getAttribute("pessoa");

            if (relatorio.equals("filmesAlugados")) {

                br.unesp.demac.bcc.soo.wsClient.Pessoa pWs = new br.unesp.demac.bcc.soo.wsClient.Pessoa();
                pWs.setNome(p.getNome());
                pWs.setCpf(p.getCpf());
                pWs.setIdPessoa(p.getIdPessoa());

                List<AluguelRel> l = relatorioAluguelCliente(pWs, false);

                StringBuilder tab = new StringBuilder("");

                tab.append("<table width='60%' align='center'>"
                        + "     <tr style='background-color:#8FBC8F'>"
                        + "         <td>Dvd</td>"
                        + "         <td>Gênero</td>"
                        + "         <td>Modalidade</td>"
                        + "         <td>Data Locação</td>"
                        + "         <td>Data Devolução</td>"
                        + "         <td>Valor</td>"
                        + "     </tr>");

                int i = 0;

                SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy");
                String mensagem = "";

                for (AluguelRel aRel : l) {

                    String background = "";

                    Date today = new Date();

                    if (today.getTime() > aRel.getDataDevolucao().toGregorianCalendar().getTime().getTime()) {

                        background = "style='background-color:#FF4500'";
                        mensagem = "<font color='red'>* Dvds que estão com devolução atrasada.</font>";

                    } else {

                        background = "onMouseOver='javascript:this.style.backgroundColor=\"#90EE90\"' onMouseOut='javascript:this.style.backgroundColor=\"\"'";
                    }

                    tab.append("<tr " + background + ">"
                            + " <td>" + aRel.getDvd().getNome() + "</td>"
                            + " <td>" + aRel.getDvd().getGenero() + "</td>"
                            + " <td>" + aRel.getDvd().getModalidade().getNome() + "</td>"
                            + " <td align='center'>" + sd.format(aRel.getAluguel().getDataLocacao().toGregorianCalendar().getTime()) + "</td>"
                            + " <td align='center'>" + sd.format(aRel.getDataDevolucao().toGregorianCalendar().getTime()) + "</td>"
                            + " <td align='center'>R$ " + aRel.getValor() + "</td></tr>");
                }

                tab.append("</table><br>" + mensagem);

                JSONObject json = new JSONObject();

                json.put("table", tab.toString());
                json.put("status", "ok");
                out.print(json.toString());

            } else if (relatorio.equals("historico")) {

                br.unesp.demac.bcc.soo.wsClient.Pessoa pWs = new br.unesp.demac.bcc.soo.wsClient.Pessoa();
                pWs.setNome(p.getNome());
                pWs.setCpf(p.getCpf());
                pWs.setIdPessoa(p.getIdPessoa());

                List<AluguelRel> l = relatorioAluguelCliente(pWs, true);

                StringBuilder tab = new StringBuilder("");

                tab.append("<table width='60%' align='center'>"
                        + "     <tr style='background-color:#8FBC8F'>"
                        + "         <td>Dvd</td>"
                        + "         <td>Gênero</td>"
                        + "         <td>Modalidade</td>"
                        + "         <td>Data Locação</td>"
                        + "         <td>Data Devolução</td>"
                        + "         <td>Data Devolvido</td>"
                        + "         <td>Valor</td>"
                        + "     </tr>");

                SimpleDateFormat sd = new SimpleDateFormat("dd/MM/yyyy");
                String mensagem = "";

                for (AluguelRel aRel : l) {

                    String background = "";

                    Date today = new Date();

                    if (today.getTime() > aRel.getDataDevolucao().toGregorianCalendar().getTime().getTime() && aRel.getDataDevolvido() == null) {

                        background = "style='background-color:#FF4500'";
                        mensagem = "<font color='red'>* Dvds que estão com devolução atrasada.</font>";

                    } else {

                        background = "onMouseOver='javascript:this.style.backgroundColor=\"#90EE90\"' onMouseOut='javascript:this.style.backgroundColor=\"\"'";
                    }

                    tab.append("<tr " + background + ">"
                            + " <td>" + aRel.getDvd().getNome() + "</td>"
                            + " <td align='center'>" + aRel.getDvd().getGenero() + "</td>"
                            + " <td align='center'>" + aRel.getDvd().getModalidade().getNome() + "</td>"
                            + " <td align='center'>" + sd.format(aRel.getAluguel().getDataLocacao().toGregorianCalendar().getTime()) + "</td>"
                            + " <td align='center'>" + sd.format(aRel.getDataDevolucao().toGregorianCalendar().getTime()) + "</td>"
                            + " <td align='center'>" + ((aRel.getDataDevolvido() != null) ? sd.format(aRel.getDataDevolvido().toGregorianCalendar().getTime()) : "Aluguel em Andamento") + "</td>"
                            + " <td align='center'>R$ " + aRel.getValor() + "</td></tr>");
                }

                tab.append("</table><br>" + mensagem);

                JSONObject json = new JSONObject();

                json.put("table", tab.toString());
                json.put("status", "ok");
                out.print(json.toString());

            } else if (relatorio.equals("ranking")) {

                Date dataInicio = null;
                Date dataFim = null;
                int quantFilmes = 0;
                XMLGregorianCalendar xmlDataFim = null;
                XMLGregorianCalendar xmlDataInicio = null;

                SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

                try {
                    dataInicio = new Date(format.parse(request.getParameter("dataInicio")).getTime());
                    dataFim = new Date(format.parse(request.getParameter("dataFim")).getTime());
                    quantFilmes = Integer.parseInt(request.getParameter("quantFilmes"));

                    GregorianCalendar cInicio = new GregorianCalendar();
                    cInicio.setTime(dataInicio);

                    xmlDataInicio = DatatypeFactory.newInstance().newXMLGregorianCalendar(cInicio);

                    GregorianCalendar cFim = new GregorianCalendar();
                    cFim.setTime(dataFim);

                    xmlDataFim = DatatypeFactory.newInstance().newXMLGregorianCalendar(cFim);

                } catch (DatatypeConfigurationException e) {

                    e.printStackTrace();

                } catch (ParseException ex) {

                    ex.printStackTrace();
                }

                List<Dvd> l = filmesMaisAlugados(xmlDataInicio, xmlDataFim, quantFilmes);
                
                StringBuilder tab = new StringBuilder("");                

                if (l.size() > 0) {

                    tab.append("<table width='60%' align='center'>"
                            + "     <tr style='background-color:#8FBC8F'>"
                            + "         <td>Rank</td>"
                            + "         <td>Dvd</td>"
                            + "         <td>Gênero</td>"
                            + "         <td>Classificação</td>"
                            + "         <td>Modalidade</td>"
                            + "         <td>Valor</td>"
                            + "         <td>Dias p/ Devolução</td>"
                            + "     </tr>");
                    
                    int i = 1;
                    
                    for(Dvd d : l){
                    
                        tab.append("<tr onMouseOver='javascript:this.style.backgroundColor=\"#90EE90\"' onMouseOut='javascript:this.style.backgroundColor=\"\"'>"
                                + "     <td align='center'>"+ (i++) +"</td>"
                                + "     <td>"+ d.getNome() +"</td>"
                                + "     <td align='center'>"+ d.getGenero() +"</td>"
                                + "     <td align='center'>"+ d.getClassificacao() +"</td>"
                                + "     <td align='center'>"+ d.getModalidade().getNome() +"</td>"
                                + "     <td align='center'> R$ "+ d.getModalidade().getValorAluguel() +"</td>"
                                + "     <td align='center'>"+ d.getModalidade().getDiasDevolucao() +"</td>");
                    }
                    

                }else{
                
                    tab.append("<font color='red'>Não foi possível gerar um Ranking dos Dvds mais alugados.</font>");
                }


                JSONObject json = new JSONObject();
                json.put("status", "ok");
                json.put("table", tab.toString());

                out.print(json.toString());

            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private java.util.List<br.unesp.demac.bcc.soo.wsClient.AluguelRel> relatorioAluguelCliente(br.unesp.demac.bcc.soo.wsClient.Pessoa pessoa, boolean tudo) {
        br.unesp.demac.bcc.soo.wsClient.LocadoraWS port = service.getLocadoraWSPort();
        return port.relatorioAluguelCliente(pessoa, tudo);
    }

    private java.util.List<br.unesp.demac.bcc.soo.wsClient.Dvd> filmesMaisAlugados(javax.xml.datatype.XMLGregorianCalendar dataInicio, javax.xml.datatype.XMLGregorianCalendar dataFim, int quantFilmes) {
        br.unesp.demac.bcc.soo.wsClient.LocadoraWS port = service.getLocadoraWSPort();
        return port.filmesMaisAlugados(dataInicio, dataFim, quantFilmes);
    }
}
